﻿using System.Data;
using EkStudio.com.bean.xml.BillMapping;
using EkStudio.com.ui.unitbill;
using EkStudio.com.bean.xml.Unit;
using System.Windows.Forms;
using System.Collections.Generic;
using EkStudio.com.common.unit;
using DevExpress.XtraGrid.Columns;

namespace EkStudio.com.ui.form.MapDataSource
{
    public partial class MapTargetForm : DevExpress.XtraEditors.XtraForm
    {

        private DataTable data = new DataTable("FieldTable");

        private BillDataMapItem Map = null;

        private ProjectRootPanel RootPanel = null;

        private BillMapUnitPanel UnitPanel = null;

        public MapTargetForm(ProjectRootPanel root, BillMapUnitPanel unit,BillDataMapItem bean)
        {
            InitializeComponent();
            InitForm(root,unit,bean);
        }

        private void InitForm(ProjectRootPanel root, BillMapUnitPanel unit, BillDataMapItem bean)
        {
            Map = bean;
            RootPanel = root;
            UnitPanel = unit;
            data.Columns.Add("caption", typeof(string));
            data.Columns.Add("key", typeof(string));
            data.Columns.Add("nodeType", typeof(string));
            data.Columns.Add("keyword", typeof(bool));
            GridListControl.DataSource = data;
            GridListView.OptionsBehavior.Editable = !unit.ReadOnly;
            RepositoryTypeNodeEdit.Items.AddRange(BeanUtil.STOCK_MAP_LIST);
        }


        new public DialogResult ShowDialog()
        {
            data.Clear();
            if (Map.MapProperties.Target == null) Map.MapProperties.Target = new BillDataMapTarget();
            if (Map.MapProperties.Target.Element == null) Map.MapProperties.Target.Element = new List<BillDataMapTargetElement>();
            if (Map.MapProperties.Target.Element.Count > 0)
            {
                foreach(BillDataMapTargetElement it in Map.MapProperties.Target.Element)
                {
                    DataRow row = data.NewRow();
                    row["caption"] = it.Caption;
                    row["key"] = it.Key;
                    row["nodeType"] = it.NodeType;
                    row["keyword"] = it.Keyword;
                    data.Rows.Add(row);
                }
            }
            GridListView.RefreshData();
            BtnSubmit.Enabled = false;
            return base.ShowDialog();
        }

        private void BtnAdd_Click(object sender, System.EventArgs e)
        {
            if (UnitPanel.ReadOnly) return;
            DataRow row = data.NewRow();
            row["caption"] = "";
            row["key"] = "";
            row["nodeType"] = "";
            row["keyword"] = false;
            data.Rows.Add(row);
            GridListView.RefreshData();
            GridListView.MoveLastVisible();
            BtnSubmit.Enabled = true;
        }

        private void BtnRemove_Click(object sender, System.EventArgs e)
        {
            if (UnitPanel.ReadOnly) return;
            if (GridListView.FocusedRowHandle >= 0)
            {
                int pevIndex = 0;
                if (GridListView.FocusedRowHandle > 0)
                {
                    pevIndex = GridListView.FocusedRowHandle - 1;
                }
                data.Rows.RemoveAt(GridListView.FocusedRowHandle);
                GridListView.RefreshData();
                if(data.Rows.Count>0) GridListView.FocusedRowHandle = pevIndex;
                BtnSubmit.Enabled = true;
            }
        }

        private void BtnSubmit_Click(object sender, System.EventArgs e)
        {
            if (UnitPanel.ReadOnly) return;
            //验证数据
            bool success = false;
            int SummaryCount = 0, MoneyCount = 0,PriceCount = 0;
            List<string> keylist = new List<string>();
            if (data.Rows.Count > 0)
            {
                foreach(DataRow row in data.Rows)
                {
                    if ("StSummary".Equals(row["nodeType"]))
                    {
                        SummaryCount++;
                    }
                    else if ("StMoney".Equals(row["nodeType"]))
                    {
                        MoneyCount++;
                    }
                    else if ("StPrice".Equals(row["nodeType"])){
                        PriceCount++;
                    }
                    string key = row["key"] as string;
                    if (!keylist.Contains(key))
                    {
                        keylist.Add(key);
                    }
                    else
                    {
                        RootPanel.ShowAlert("错误", "结存字段名称不可重复");
                        break;
                    }
                }
                if(keylist.Count == data.Rows.Count)
                {
                    if (SummaryCount == 0)
                    {
                        RootPanel.ShowAlert("错误", "[StSummary]类型字段至少存在1个");
                    }
                    else if (MoneyCount > 1)
                    {
                        RootPanel.ShowAlert("错误", "[StMoney]类型字段最多只能存在1个");
                    }
                    else if (PriceCount > 1)
                    {
                        RootPanel.ShowAlert("错误", "[StPrice]类型字段最多只能存在1个");
                    }
                    else if (PriceCount == 1 && MoneyCount == 0)
                    {
                        RootPanel.ShowAlert("错误", "[StPrice]存在时,[StMoney]必须同时存在");
                    }
                    else
                    {
                        success = true;
                    }
                }
                
            }
            if (success)
            {
                Map.MapProperties.Target.Element.Clear();
                foreach (DataRow row in data.Rows)
                {
                    BillDataMapTargetElement it = new BillDataMapTargetElement();
                    it.Caption = row["caption"] as string;
                    it.Key = row["key"] as string;
                    it.NodeType = row["nodeType"] as string;
                    it.Keyword = (bool)row["keyword"];
                    Map.MapProperties.Target.Element.Add(it);
                }
                DialogResult = DialogResult.OK;
                Close();
            }
        }

        private void BtnCancel_Click(object sender, System.EventArgs e)
        {

        }

        private void GridListView_CellValueChanging(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            if (e.Column.FieldName == "keyword")
            {
                if (data.Rows[e.RowHandle]["nodeType"].Equals(BeanUtil.STOCK_MAP_FIELD_SUMMARY))
                {
                    int row = 0;
                    foreach (DataRow dt in data.Rows)
                    {
                        if (row != e.RowHandle)
                        {
                            dt["keyword"] = false;
                        }
                        row++;
                    }
                    GridListView.RefreshData();
                }
                
            }
            else if(e.Column.FieldName == "nodeType")
            {
                if (!e.Value.Equals(BeanUtil.STOCK_MAP_FIELD_SUMMARY))
                {
                    data.Rows[e.RowHandle]["keyword"] = false;
                    GridListView.RefreshData();
                }
            }
        }

        private void GridListView_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            BtnSubmit.Enabled = true;
            if(e.Column.FieldName == "nodeType")
            {
                if (!e.Value.Equals(BeanUtil.STOCK_MAP_FIELD_SUMMARY))
                {
                    foreach (GridColumn col in GridListView.Columns)
                    {
                        if (col.FieldName == "keyword")
                        {
                            col.OptionsColumn.AllowEdit = false;
                            break;
                        }
                    }
                }
                else
                {
                    foreach (GridColumn col in GridListView.Columns)
                    {
                        if (col.FieldName == "keyword")
                        {
                            col.OptionsColumn.AllowEdit = true;
                            break;
                        }
                    }
                }
            }
            
        }

        private void GridListView_SelectionChanged(object sender, DevExpress.Data.SelectionChangedEventArgs e)
        {
            
        }

        private void GridListView_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            
            if (e.FocusedRowHandle >= 0)
            {
                if (!data.Rows[e.FocusedRowHandle]["nodeType"].Equals(BeanUtil.STOCK_MAP_FIELD_SUMMARY))
                {
                    
                    foreach (GridColumn col in GridListView.Columns)
                    {
                        if (col.FieldName == "keyword")
                        {
                            col.OptionsColumn.AllowEdit = false;
                            break;
                        }
                    }
                }
                else
                {
                    foreach (GridColumn col in GridListView.Columns)
                    {
                        if (col.FieldName == "keyword")
                        {
                            col.OptionsColumn.AllowEdit = true;
                            break;
                        }
                    }
                }
            }
        }
    }
}